package com.fang.strategy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/4/22 4:01 下午
 **/
@Component
public class StrategyFactory implements InitializingBean, BeanFactoryAware {

    private DefaultListableBeanFactory defaultListableBeanFactory;

    private final List<CalcNumStrategy> strategyList = new ArrayList<>();

    /**
     * Spring加载Bean 实例化后，InitializingBean.setBeanFactory自定义初始化
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    /**
     * BeanFactoryAware.afterPropertiesSet 完成最终初始化
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        strategyList.addAll(defaultListableBeanFactory.getBeansOfType(CalcNumStrategy.class).values());
    }

    public CalcNumStrategy create(CalcTypeEnum calcType) {
        Optional<CalcNumStrategy> calcStrategy = strategyList.stream().filter(strategy -> strategy.support(calcType)).findFirst();
        Assert.isTrue(calcStrategy.isPresent(), "can not find support CalcStrategy");
        return calcStrategy.get();
    }
}
